import 'dart:convert';

import 'package:device_calendar/device_calendar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xiaozhou_ams_flutter/user/registration_page.dart';
import 'package:xiaozhou_ams_flutter/todoListInterface.dart';
import 'package:xiaozhou_ams_flutter/tools.dart';
import 'package:xiaozhou_ams_flutter/userprofile/createFaceInterfacePage.dart';
import 'Face/FaceRecognitionScreen.dart';
import 'MainPage.dart';
import 'UserProfilePage.dart';
import 'api_client.dart';
import 'user/login.dart';
import 'memo_list.dart';
import 'userprofile/message_page.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '悦享老年',
      initialRoute: '/',
      routes: {
          '/': (context) => const InitialPage(),
          '/main':(context) => const MainPage(),
          '/memo': (context) => const MemoListPage(),
          '/todo': (context) =>  const ToDoListScreen(),
          '/faceSignIn': (context) => const FaceSignInScreen(),
          '/userProfile': (context) => const UserProfilePage(),
          '/login':  (context) => const LoginPage(),
          '/Registration':  (context) => const RegistrationPage(),
          '/userprofile/MessagePage': (context) => const MessagePage(),
          '/userprofile/createFaceInterfacePage':(context) => const createFaceInterfacePage(cameras: [],),
      },
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('zh', 'CN'), // 支持中文
      ],
    );
  }
}

// 初始页面
class InitialPage extends StatefulWidget {
  const InitialPage({super.key});

  @override
  _InitialPageState createState() => _InitialPageState();

}

class _InitialPageState extends State<InitialPage> {
  final DeviceCalendarPlugin _deviceCalendarPlugin = DeviceCalendarPlugin();

  Future<bool> requestPermissions() async {
    var permissionsGranted = await _deviceCalendarPlugin.hasPermissions();
    if (permissionsGranted.isSuccess && !permissionsGranted.data!) {
      permissionsGranted = await _deviceCalendarPlugin.requestPermissions();
      if (!permissionsGranted.isSuccess || !permissionsGranted.data!) {
        return false;
      }
    }
    return true;
  }
  @override
  void initState() {
    super.initState();
    _checkLoginStatus();
  }

  Future<void> clearToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('userToken');
  }

  Future<void> _checkLoginStatus() async {
    await requestPermissions();
    // 模拟长时间操作的延迟
    await Future.delayed(const Duration(seconds: 5));
    final prefs = await SharedPreferences.getInstance();
    final String? token = prefs.getString('userToken');

    // 实现判断Token是否失效的逻辑

    if (token != null && token.isNotEmpty) {
      // 用户已登录
      try {
        final fromData = {
          'token': token
        };
        final response = await ApiClient.sendPostRequest('util/tokenVerification',fromData);
        if (response != null) {
          final jsonMap = json.decode(response);
          bool success = jsonMap['success'];

          if (success) {
            String newToken = jsonMap['data'];
            await clearToken();
            await prefs.setString('userToken', newToken); // 更新Token
            if (mounted) {
              Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(builder: (context) => const MainPage(initialIndex: 3)), // 设定返回的页面和参数
                    (Route<dynamic> route) => false, // 移除所有之前的路由
              );
            }
          } else {
            if (mounted) {
              Navigator.pushReplacementNamed(context, '/login');
            }
          }
        } else {
          if (mounted) {
            Navigator.pushReplacementNamed(context, '/login');
          }
        }
      } catch (error) {
        if (kDebugMode) {
          print('Token verification failed: $error');
        }
        if (mounted) {
          Navigator.pushReplacementNamed(context, '/login');
        }
        SnackbarHelper.showToast("系统错误，请联系统管理员！");
      }
    } else {
      // 用户未登录
      if (mounted) {
        Navigator.pushReplacementNamed(context, '/login');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Image.asset(
                'assets/loading.gif', // 动图的路径
                width: 200, // 动图的宽度
                height: 200, // 动图的高度
              ),
              const SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

}




